package com.wnhoo.smartfishtank.fishtank;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.wnhoo.smartfishtank.R;
import com.wnhoo.smartfishtank.api.LM_PlugAPIs;
import com.wnhoo.smartfishtank.api.data.DataPlug;
import com.wnhoo.smartfishtank.api.data.LM_DataPlugList;
import com.wnhoo.smartfishtank.app.LMAPP;
import com.wnhoo.smartfishtank.base.BaseActivity;
import com.wnhoo.smartfishtank.base.ListViewCompat;
import com.wnhoo.smartfishtank.ble.BleService;
import com.wnhoo.smartfishtank.contants.adapter.AdapterDataPlug;

import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

public class DataPlug_ListActivity extends BaseActivity implements
        BaseActivity.InitHeaderListener, AdapterDataPlug.OnItemTimingListener{

    private ListViewCompat dataplug_list;
    private AdapterDataPlug adapterDataPlug;
    private RelativeLayout dataplug_list_defult;
    private ImageView dataplug_list_icon_press;
    private RelativeLayout dataplug_add_code_btn, dataplug_add_wifi_btn, dataplug_add_bluetooth_btn;
    private final String TAG = "DataPlug_ListActivity";
    private List<DataPlug> data_plug_list;
    private PopupWindow popupWindow;
    private View view;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_data_plug__list);
        setOnInitListener(this);
        initView();
        initData();
    }

    @Override
    protected void onStart() {
        super.onStart();
        Log.i(TAG,"start方法");
        adapterDataPlug.notifyDataSetChanged();
//        从服务器请求列表数据
        requestDataPlugList();
    }

    @Override
    protected void onResume() {
        super.onResume();

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        System.exit(0);
    }

    @Override
    public void initView() {
        super.initView();
        dataplug_list = (ListViewCompat) findViewById(R.id.dataplug_list);
        dataplug_list_defult = (RelativeLayout) findViewById(R.id.dataplug_list_defult);
        dataplug_list_icon_press = (ImageView) findViewById(R.id.dataplug_list_icon_press);
        dataplug_list_defult.setOnClickListener(this);
    }

    private void initData() {
        data_plug_list = LMAPP.data_plug_list;
        adapterDataPlug = new AdapterDataPlug(data_plug_list, this);
        adapterDataPlug.setOnItemTimingListener(this);
        dataplug_list.setAdapter(adapterDataPlug);

    }

    private final static int MSG_HTTP_SEND_RESULT = 1;
    Handler handler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            // TODO Auto-generated method stub
            super.handleMessage(msg);

            switch (msg.what) {
                case MSG_HTTP_SEND_RESULT:
                    //handlerSendResult(msg);
                    LM_DataPlugList lm_dataPlugList = (LM_DataPlugList) msg.obj;
                    if (lm_dataPlugList.getError_code() == 0|| lm_dataPlugList.getError_code() == 403 || lm_dataPlugList.getError_code() == 412) {
                        if(lm_dataPlugList.getData()==null){
//                            ShowToastUtil.show(getApplication(), "服务器数据为空");
                            Log.i(TAG,"服务器数据为空");
                            return;
                        }
                        if(lm_dataPlugList.getData().isEmpty()){
                            Log.i(TAG,"服务器数据为空");
                            return;
                        }
                        if (lm_dataPlugList.getData() != null) {
                            data_plug_list.clear();
                            for (DataPlug data : lm_dataPlugList.getData()) {
                                data_plug_list.add(data);
                            }
                        }
                        LMAPP.saveMemoryPlugToSPF();
                        adapterDataPlug.notifyDataSetChanged();
                    } else {
//                        ShowToastUtil.show(getApplication(), "从服务器请求列表失败");
                    }
                    break;

            }
        }
    };
    public static BleService mService;
//    private ServiceConnection mServiceConnection = new ServiceConnection() {
//        @Override
//        public void onServiceConnected(ComponentName name, IBinder service) {
//            Log.i("mic", "===================service" + service);
//            mService = ((BleService.BleServiceBinder) service).getService();
//            if (mService.initialize() == false) {
//                finish();
//            } else {
//                mService.scanLeDevice(true);
//            }
//            if (mService != null && address != null) {
//                boolean isInitSucc = mService.connect(address);
//                Log.i(tag, "isInitSucc" + "是否连接成功" + isInitSucc);
//            }
//        }
//
//        @Override
//        public void onServiceDisconnected(ComponentName name) {
//            mService = null;
//        }
//    };

    //请求设备列表
    public void requestDataPlugList() {
        new Thread() {
            @Override
            public void run() {
                super.run();
                try {
                    LM_DataPlugList lm_dataPlugList = LM_PlugAPIs.deviceList(true, LMAPP.token_default);
                    Log.i(TAG, "lm_dataPlugList" + lm_dataPlugList.getData().toString());
                    sendMessageToUI(MSG_HTTP_SEND_RESULT, lm_dataPlugList);
                } catch (Exception e) {
                    e.printStackTrace();
//                    sendMessageToUI(MSG_HTTP_SEND_EXCEPTION, e);
                }
            }
        }.start();
    }

    public void sendMessageToUI(int what, Object obj) {

        Message message = Message.obtain();
        message.what = what;
        message.obj = obj;
        handler.sendMessage(message);
    }
    @Override
    public void onClick(View view) {
        super.onClick(view);
        switch (view.getId()) {
            case R.id.dataplug_list_defult:
//                if (dataplug_list.getVisibility() == View.VISIBLE) {
//                    dataplug_list.setVisibility(View.GONE);
//                    dataplug_list_icon_press.setImageResource(R.drawable.ther_arrows);
//                } else {
//                    dataplug_list.setVisibility(View.VISIBLE);
//                    dataplug_list_icon_press.setImageResource(R.drawable.dataplug_listshow_icon);
//                }
                break;
            case R.id.dataplug_add_code_btn:

                break;
            case R.id.dataplug_add_wifi_btn:
                startActivity(new Intent(this, AddDeviceActivity.class));
                break;
            case R.id.dataplug_add_bluetooth_btn:
                break;
        }
    }
    /**
     * 显示
     *
     * @param parent
     */
    private void showWindow(View parent) {

        if (popupWindow == null) {
            LayoutInflater layoutInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            view = layoutInflater.inflate(R.layout.activity_custom_popwindow_group_list, null);
            dataplug_add_code_btn = (RelativeLayout) view.findViewById(R.id.dataplug_add_code_btn);
            dataplug_add_wifi_btn = (RelativeLayout) view.findViewById(R.id.dataplug_add_wifi_btn);
            dataplug_add_bluetooth_btn = (RelativeLayout) view.findViewById(R.id.dataplug_add_bluetooth_btn);

            dataplug_add_code_btn.setOnClickListener(this);
            dataplug_add_wifi_btn.setOnClickListener(this);
            dataplug_add_bluetooth_btn.setOnClickListener(this);
            popupWindow = new PopupWindow(view, (int) getResources().getDimension(R.dimen.groupadapter_width), (int) getResources().getDimension(R.dimen.groupadapter_height));
        }
        // 使其聚集
        popupWindow.setFocusable(true);
        // 设置允许在外点击消失
        popupWindow.setOutsideTouchable(true);
        // 这个是为了点击“返回Back”也能使其消失，并且并不会影响你的背景
        popupWindow.setBackgroundDrawable(new BitmapDrawable());
        WindowManager windowManager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
        // 显示的位置为:屏幕的宽度的一半-PopupWindow的高度的一半
        int xPos = windowManager.getDefaultDisplay().getWidth() / 2
                - popupWindow.getWidth() / 2;

        Log.i("coder", "windowManager.getDefaultDisplay().getWidth()/2:"
                + windowManager.getDefaultDisplay().getWidth() / 2);
        //
        Log.i("coder", "popupWindow.getWidth()/2:" + popupWindow.getWidth() / 2);
        Log.i("coder", "xPos:" + xPos);
        popupWindow.showAsDropDown(parent, xPos, 0);
    }
    @Override
    public void OnSetTitle(TextView t) {
        t.setText(getStringXml(R.string.mydevice));
//        t.setTextColor(0xff525252);
        t.setTextColor(this.getResources().getColor(R.color.ther_text_color));
    }

    @Override
    public void OnSetLeftView(Button btn) {

    }

    @Override
    public void OnSetRightView(Button btn) {
        btn.setVisibility(View.VISIBLE);
        btn.setBackgroundResource(R.drawable.dataplug_add_selector);
    }

    @Override
    public void OnSetLeftOnclick(View view) {

    }

    @Override
    public void OnSetRightOnclick(View view) {
        startActivity(new Intent(this, AddDeviceActivity.class));
    }

    @Override
    public void onSetbackground(View view) {
        view.setBackgroundResource(R.drawable.solid_shadow);
    }

    /**
     * 显示修改
     */
    private void showAlterNameView(final int position) {
        View view_edit = View.inflate(this, R.layout.sub_edittext, null);
        final EditText editview_name = (EditText) view_edit.findViewById(R.id.editview_name);
        editview_name.setText(LMAPP.dataPlug.getTitle());
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("选择进入的设备").setView(view_edit)
                .setNegativeButton("灯", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        startActivity(new Intent(DataPlug_ListActivity.this, ColorActivity.class));
                    }
                });
        builder.setPositiveButton("加热器", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                startActivity(new Intent(DataPlug_ListActivity.this, ThermostatActivity.class));
            }
        });
        builder.show();
    }

    @Override
    public boolean ItemOnclick(int position, View view, int category) {
        if(LMAPP.data_plug_list.isEmpty()){
            Log.i(TAG,"当前列表为空");
            LMAPP.data_plug_list.clear();
            adapterDataPlug.notifyDataSetChanged();
            return false;
        }
        LMAPP.dataPlug = LMAPP.data_plug_list.get(position);
//        switch (LMAPP.data_plug_list.get(position).getType()){
//            case 1005:
//                showAlterNameView(position);
//                break;
//            case 1010:
//                startActivity(new Intent(DataPlug_ListActivity.this, ThermostatActivity.class));
//                break;
//            case 1011:
                startActivity(new Intent(DataPlug_ListActivity.this, ColorActivity.class));
//                break;
//        }
        return false;
    }

    /**
     * 菜单、返回键响应
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // TODO Auto-generated method stub
        if(keyCode == KeyEvent.KEYCODE_BACK)
        {
            exitBy2Click(); //调用双击退出函数
        }
        return false;
    }
    /**
     * 双击退出函数
     */
    private static Boolean isExit = false;

    private void exitBy2Click() {
        Timer tExit = null;
        if (isExit == false) {
            isExit = true; // 准备退出
            Toast.makeText(this, getStringXml(R.string.exit), Toast.LENGTH_SHORT).show();
            tExit = new Timer();
            tExit.schedule(new TimerTask() {
                @Override
                public void run() {
                    isExit = false; // 取消退出
                }
            }, 2000); // 如果2秒钟内没有按下返回键，则启动定时器取消掉刚才执行的任务

        } else {
            finish();
        }
    }

}
